<?php
declare (strict_types=1);

namespace app\backend\controller\v4;

use app\api\validate\LoginValidate;
use app\common\models\BackendPermission;
use app\common\models\BackendMember as BackendMemerModel;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Request;

class BackendMember extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $id = input('id/d', 0);
        return $id;
    }

    /**
     * 获取角色权限
     */
    public function getRole()
    {
        //获取当前域名
        $request = Request::instance();
        $domain = $request->domain();
        // 获取用户角色信息
        $userRole = BackendMemerModel::where(['id' => $this->user_id])->field('id,role_id')
            ->with(['role', 'role_permission'])
            ->withAttr('role_permission.permission_id', function ($val, $data) {
                return BackendPermission::where(['id' => $val])->field('id,title,action,status,pid,component,icon')->find()->toArray();
            })
            ->find();
//        $userRole->avatar = config("app.domain_url") . $userRole->avatar;
        // 定义权限新数组
        $role_permission_list = [];
        foreach ($userRole->role_permission as $k => $v) {
            $role_permission_list[$k]['id'] = $v->permission_id['id'];
            $role_permission_list[$k]['name'] = $v->permission_id['title'];
            $role_permission_list[$k]['path'] = $v->permission_id['action'];
            $role_permission_list[$k]['pid'] = $v->permission_id['pid'];
            $role_permission_list[$k]['component'] = $v->permission_id['component'];
            $role_permission_list[$k]['meta'] = ['title' => $v->permission_id['title'], 'icon' => 'table'];
        }
        // 获取权限树，默认缓存2个小时
        $cache_role_permission_list = Cache::get('backend_' . $this->user_id . ':role_permission');
        if (!$cache_role_permission_list) {
            // 通过方法获取权限树
            $cache_role_permission_list = $role_permission_list = getTree($role_permission_list);
            Cache::set('backend_' . $this->user_id . ':role_permission', $role_permission_list, 7200);
        }
        // 删除重复、不使用数据
        unset($userRole['role_permission']);
        //修改数组下标
        foreach ($cache_role_permission_list as $k => &$v) {
            if (!empty($v['children'])) {
                $v['children'] = array_merge($v['children']);
//                $v['redirect'] = $v['path'] . '/' . $v['children'][0]['path'];
                $v['redirect'] = $v['children'][0]['path'];
                foreach ($v['children'] as &$value) {
                    unset($value['id']);
                    unset($value['pid']);
                    unset($value['level']);
                    if (empty($value['children'])) {
                        unset($value['children']);
                    } else {
                        foreach ($value['children'] as &$vvv) {
                            unset($vvv['id']);
                            unset($vvv['pid']);
                            unset($vvv['level']);
                            if (empty($vvv['children'])) {
                                unset($vvv['children']);
                            }
                        }
                        $value['children'] = array_merge($value['children']);
                    }
                }
            } else {
                unset($v['children']);
            }
            unset($v['id']);
            unset($v['pid']);
            unset($v['level']);
        }
        $cache_role_permission_list = array_merge($cache_role_permission_list);
        // 返回数据
        return sucessMsg(200, '获取成功！', $cache_role_permission_list);
    }

    /***
     * 获取用户信息
     */
    public function memberInfo()
    {
        //获取当前域名
        $request = Request::instance();
        $domain = $request->domain();
        // 获取用户角色信息
        $userRole = BackendMemerModel::where(['id' => $this->user_id])->field('id,role_id,username,avatar')
            ->with(['role'])
            ->find();
        $userRole->role_name = $userRole->role->role_name;
        $userRole->avatar = 'http://39.98.186.60/' . $userRole->avatar;
        unset($userRole->role);
        return sucessMsg(200, '获取成功！', $userRole);
    }

    /***
     * 清除缓存
     */
    public function clearCache()
    {
        Cache::clear();
        return sucessMsg(200, '请求成功');
    }

    /***
     * 退出登录
     */
    public function loginOut()
    {
        return sucessMsg(200, '请求成功');
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
//    public function read()
//    {
//        //搜索
//        $where1 = input('username');
//        $where2 = input('account');
//        $role_id = input('role_id/d');
//
//        $model = new BackendMemerModel();
//        $page = input('page/d', 1);
//        $size = 10;
//        $datas = $model
//            ->with(['role'])
//            ->where('role_id', '<>', $role_id)
//            ->where(function ($query) use ($where1, $where2) {
//                if ($where1) {
//                    $query->where('username', 'like', '%' . $where1 . '%');
//                }
//                if ($where2) {
//                    $query->where('account', 'like', '%' . $where2 . '%');
//                }
//            })
//            ->page($page, $size)
//            ->select();
//        foreach ($datas as $data) {
////            $data['avatar'] = 'http://en.test.1demo.cc.com/' . $data['avatar'];
//            $data['role_name'] = $data['role']['role_name'];
//            unset($data['role']);
//        }
//        $rows = count($model->select()->toArray());
//        $maxPage = ceil($rows / $size);
//        return sucessMsg(200, '获取成功！', ['data' => $datas, 'page' => $page, 'maxPage' => $maxPage, 'rows' => $rows]);
//    }
    public function read()
    {
        //搜索
        $where1 = input('username');
        $where2 = input('account');
        $this->role_id = input('role_id/d', 3);

        $model = new BackendMemerModel();
        $page = input('page/d', 1);
        $size = 10;
        $datas = $model
            ->with(['role'])
            ->where('is_del', 0)
            ->where('role_id', '=', $this->role_id)
            ->where(function ($query) use ($where1, $where2) {
                if ($where1) {
                    $query->where('username', 'like', '%' . $where1 . '%');
                }
                if ($where2) {
                    $query->where('account', 'like', '%' . $where2 . '%');
                }
            })
            ->order('id','desc')
            ->page($page, $size)
            ->select();
        foreach ($datas as $data) {
            $data['role_name'] = $data['role']['role_name'];
            unset($data['role']);
        }
        $rows = count($model->where('role_id', $this->role_id)->select());
        $maxPage = ceil($rows / $size);
        return sucessMsg(200, '获取成功！', ['data' => $datas, 'page' => $page, 'maxPage' => $maxPage, 'rows' => $rows]);
    }


    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $roleModel = new \app\common\model\BackendRole();
        $datas = $roleModel->where('status', 1)->field('id,role_name')->select();
        return sucessMsg(200, '获取成功！', $datas);

    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(\think\Request $request)
    {
        $postData = input('post.');
        try {
            //  验证参数
            validate(LoginValidate::class)->scene('save')->check($postData);
            $user = new \app\common\model\BackendMember();
            $memberInfo = $user->fetchInfoByWhere(['account' => $postData['account']], 'id,account');
            if (!empty($memberInfo)) {
                return errMsg(422, '账号已存在！');
            }
            $postData['salt'] = getRandStr(6);
            $postData['password_hash'] = makePassword($postData['password'], $postData['salt']);
            // 获取表单上传文件
            $file = request()->file('avatar');
            if (!empty($file)) {
                // 上传
                $savename = \think\facade\Filesystem::disk('public')->putFile('/uploads', $file);
                $postData['avatar'] = $savename;
            }
            if ($user->save($postData)) {
                return sucessMsg(200, '添加成功');
            }
            return errMsg(422, '添加失败');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @return \think\Response
     */
    public function edit()
    {
        //
        $model = new BackendMemerModel();
        $id = input('get.id/d');
        if (empty($id)) {
            return errMsg(422, 'id不能为空');
        }
        $data = $model->where('id', $id)->find();
        if (empty($data))
            return errMsg(422, '无效id');
        return sucessMsg(200, '获取成功！', $data);
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function update(Request $request)
    {
        $postData = input('post.');
        try {
            //  验证参数
            validate(LoginValidate::class)->scene('update')->check($postData);
            $model = new \app\common\model\BackendMember();
            if (!empty($postData['password'])) {
                $postData['salt'] = getRandStr(6);
                $postData['password_hash'] = makePassword($postData['password'], $postData['salt']);
            }
            unset($postData['password']);
            // 获取表单上传文件
            $file = request()->file('avatar');
            if (!empty($file)) {
                // 上传
                $savename = \think\facade\Filesystem::disk('public')->putFile('/uploads', $file);
                $postData['avatar'] = $savename;
            }
            $cate = $model->where('id', $postData['id'])->find();
            if ($cate->save($postData))
                return sucessMsg(200, '修改成功');
            return sucessMsg(422, '修改失败');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 删除指定资源
     *
     * @return \think\Response
     */
    public function delete()
    {
        //
        $model = new \app\common\model\BackendMember();
        $id = input('id/d', 0);
        if (empty($id)) {
            return errMsg(422, 'id不能为空');
        }
        $data = $model->where('id', $id)->find();
        if (empty($data))
            return errMsg(422, '无效id');
        if (BackendMemerModel::destroy($id)) {
            return sucessMsg(200, '删除成功！');
        }
        return errMsg(422, '删除失败');
    }

    public function membercount()
    {
        $model = new \app\common\model\BackendMember();
        $count = count($model->select());
        return sucessMsg(200, '获取成功', $count);
    }

}